package com.hs.auth.viewmodel

import android.graphics.Bitmap
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hs.ZaFingerBitmapUtils
import com.hs.ZaFingerprintHelper
import com.hs.common.dto.SysUserDto
import com.hs.common.repository.IUserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 *  指纹注册
 */
@HiltViewModel
class RegisterByFingerViewModel
@Inject constructor(
    private  var userService : IUserRepository,
    private var fingerprintHelper: ZaFingerprintHelper
) : ViewModel() {

    val liveData = MutableLiveData<Int>()
    val errorLiveData = MutableLiveData<String>()
    val imageLiveData = MutableLiveData<Bitmap>()
    val liveUpdateData = MutableLiveData<Int>()

    fun updateByFingerId(fingerId : Int,sysUserDto: SysUserDto){

       viewModelScope.launch(Dispatchers.IO){
            var oldFingerId = sysUserDto.featureId
            sysUserDto.featureId =fingerId
             var  updateId = userService.updateUser(sysUserDto)
             println("更新用户信息：${updateId}")
             try {
                 if (updateId<=0){ // 更新不成功 删除指纹
                     fingerprintHelper.deleteByFingerId(fingerId)
                 }else{
                   // 删除旧的指纹
                   oldFingerId?.let { if (oldFingerId!! >1) fingerprintHelper.deleteByFingerId(oldFingerId)}
                 }
             }catch (e:Exception){
                 e.toString()
                 println("${e.localizedMessage}")
             }
           withContext(Dispatchers.Main){
               liveUpdateData.value = updateId
           }
       }

    }

    /**
     * 指纹注册
     */
    fun registerByFinger(){

        viewModelScope.launch(Dispatchers.IO){
//            stopUsb()
//            delay(200)
//           openUsbDev()
            var featureId =  userService.getMaxFeatureId()
            fingerprintHelper.registerFingerprint(featureId+1).collect{
                var mBitmap : Bitmap? = null
                withContext(Dispatchers.Main){
                    println(it.status)
                    if (it.status == 0){
                        liveData.value = it.featureId
                        println("注册指纹成功：指纹id:${it.featureId}")
                        errorLiveData.value = it.msg
                    }else{
                        if(!TextUtils.isEmpty(it.msg)){
                            errorLiveData.value = it.msg
                        }
                    }
                    if (it.imageData != null){
                        mBitmap = ZaFingerBitmapUtils.getFingerBitmap(it.imageData, 256, it.imageLen!!/256)
                        if (mBitmap != null){
                            imageLiveData.value = mBitmap
                        }
                    }
                }
            }
        }
    }


    /**
     * 打开指纹串口
     */
    fun openUsbDev(){
        viewModelScope.launch(Dispatchers.IO) {
            fingerprintHelper.stop()
            val status = fingerprintHelper.openDev()
            if (status == 1 ){
                registerByFinger()
            }else{
                withContext(Dispatchers.Main){
                    errorLiveData.value = "指纹模块初始化失败:${status}"
                }
            }
        }
    }

    /**
     * 停止指纹串口
     */
    fun stopUsbDev(){
        viewModelScope.launch(Dispatchers.IO) {
            fingerprintHelper.stop()
            fingerprintHelper.closeDev()
        }
    }

    /**
     * 停止
     */
    fun stopUsb(){
        viewModelScope.launch(Dispatchers.IO) {
            fingerprintHelper.stop()
        }
    }

    /**
     *  删除
     */
//    fun deleteFormUsb(){
//
//    }


}